import { ApolloClient, InMemoryCache, createHttpLink } from '@apollo/client/core'
import { setContext } from '@apollo/client/link/context'

const httpLink = createHttpLink({
  uri: '/api/graphql', // 使用相对路径，Vite 会处理代理
})

const authLink = setContext((_, { headers }) => {
  // 从 localStorage 获取 token
  const token = localStorage.getItem('token')
  // 返回带有认证头的 headers
  return {
    headers: {
      ...headers,
      authorization: token ? `${token}` : "",
    }
  }
})

const cache = new InMemoryCache()

export const apolloClient = new ApolloClient({
  link: authLink.concat(httpLink),
  cache,
})
